package com.etoak.service.impl;

import cn.hutool.crypto.digest.MD5;
import com.etoak.common.core.constant.CommonConstant;
import com.etoak.common.core.exception.CustomException;
import com.etoak.common.jwt.MyJwtUtil;
import com.etoak.common.redis.service.RedisService;
import com.etoak.dto.LoginDTO;
import com.etoak.entity.User;
import com.etoak.mapper.UserMapper;
import com.etoak.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.vo.TokenVO;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author etoak
 * @since 2025-07-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    RedisService redisService;

    @Override
    public TokenVO login(LoginDTO loginDTO) {
        String code = redisService.get(CommonConstant.CODE_REDIS_KEY_PREFIX + loginDTO.getUuid());
        if (!StringUtils.equalsIgnoreCase(code,loginDTO.getCode())) {
            throw new CustomException("验证码错误或失效!");
        }
        String password = MD5.create().digestHex(loginDTO.getPassword());
        User user = lambdaQuery().eq(User::getUsername, loginDTO.getUsername())
                .eq(User::getPassword, password)
                .one();
        if (ObjectUtils.isEmpty(user)) {
            throw new CustomException("用户名或密码错误");
        }
        Map<String,Object> claimsMap = new HashMap<>();
        claimsMap.put("username", user.getUsername());
        claimsMap.put("id", user.getId());
        String jwt = MyJwtUtil.create(claimsMap);
        return new TokenVO(user.getUsername(),jwt);
    }
}
